package com.ly.hotel;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Array;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import com.ly.hotel.adaptor.AtvUtil;
import com.ly.hotel.adaptor.HardwareInterface;
import com.ly.hotel.common.Constants;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.MyKeyEventCode;
import com.ly.hotel.common.MyLogsManager;
import com.ly.hotel.common.SharedPreferencesConfig;
import com.ly.hotel.common.SysConf;
import com.ly.hotel.ijkplayer.debug.PlayerManager;
import com.ly.hotel.ijkplayer.widget.media.IjkVideoView;
import com.ly.hotel.model.HomeAdVideoBean;
import com.ly.hotel.model.Serve;
import com.ly.hotel.msgevent.GetIntro;
import com.ly.hotel.msgevent.GetScrollMessage;
import com.ly.hotel.msgevent.GetWebInterfaceUrlEvent;
import com.ly.hotel.msgevent.UpdateBottomView;
import com.ly.hotel.msgevent.UpdateInterfaceEvent;
import com.ly.hotel.msgevent.UpdateIntro;
import com.ly.hotel.msgevent.UpdateYouhuiMsgEvent;
import com.ly.hotel.service.MyCloudBackService;
import com.ly.hotel.service.SPABackService;
import com.ly.hotel.spainterface.jg.ActivityCollector;
import com.ly.hotel.spainterface.jg.JgActivity;
import com.ly.hotel.spainterface.jxd.activity.JxdJSActivity;
import com.ly.hotel.spainterface.jxd.activity.JxdXiaoFeiActivity;
import com.ly.hotel.spainterface.jyt.JytXiaoFeiActivity;
import com.ly.hotel.spainterface.jyt.activity.JytJSActivity;
import com.ly.hotel.spainterface.nm.NmXiaoFeiActivity;
import com.ly.hotel.spainterface.pp.activity.PPJSActivity;
import com.ly.hotel.spainterface.pp.activity.PPXFActivity;
import com.ly.hotel.util.BtnCfgUtil;
import com.ly.hotel.util.ProcessWaitingUtil;
import com.ly.hotel.util.ToastUtil;
import com.ly.hotel.util.bugtrace.CrashHandler;
import com.ly.hotel.view.InitActivity;
import com.ly.hotel.view.common.LegalDeclarationDialog;
import com.ly.hotel.view.fragments.about.AboutDialog;
import com.ly.hotel.view.fragments.game.GameActivity;
import com.ly.hotel.view.fragments.intro.IntroActivity;
import com.ly.hotel.view.fragments.music.MusicActivity;
import com.ly.hotel.view.fragments.query.FunctionDialog;
import com.ly.hotel.view.fragments.vod.EpisodeActivity;
import com.ly.hotel.view.fragments.vod.VodActivity;
import com.ly.hotel.view.fragments.youhui.YouhuiDialog;
import com.ly.hotel.view.message.MessageActivity;
import com.ly.hotel.view.userLogin.UserLoginActivity;
import com.ly.hotel.model.Device;
import com.ly.hotel.model.LiveManagement;
import com.ly.hotel.msgevent.HeaderUpdateEvent;
import com.ly.hotel.msgevent.LoginEvent;
import com.ly.hotel.msgevent.SendLogEvent;
import com.ly.hotel.msgevent.SyncCallEvent;
import com.ly.hotel.service.SPAService;
import com.ly.hotel.util.AppUtil;
import com.ly.hotel.util.HttpRequestFailException;
import com.ly.hotel.util.NetworkStateChecker;
import com.ly.hotel.util.WebInstaller;
import com.ly.hotel.view.common.CustomDialog;
import com.tencent.bugly.crashreport.CrashReport;

import de.greenrobot.event.EventBus;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.security.keystore.KeyNotYetValidException;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

public class TabHostActivity extends MyBaseActivity implements PlayerManager.PlayerStateListener {
    private static String TAG = "TabHostActivity";

    public static final int START_SETTING = 1;
    public static final int CHANGE_BG = 2;
    public static final int UPDATE_HEADER = 3;
    public static final int START_INIT = 4;
    public static final int FLASH_LAYOUT = 5;
    public static final int LOGIN = 7;
    public static final int CHECK_INVALID_DAY = 10;
    public static final int SHOW_LOGIN_DIALOG = 11;
    public static final int SHOW_AUTH_TIPS = 12;
    public static final int UDP_REV_DATA = 15;
    public static final int HIDE_MENU = 99;


    private MyApplication app;

    private boolean isUnLoginTipsed = false;
    public Builder b;// 主机没注册或者停用的提示框
    public AlertDialog aDialog = null;// 主机没注册或者停用的提示框
    private boolean isLoginfailBefore = false;

    private ThisHandler handlerMsg = new ThisHandler(this);
    private Timer login_in_timer = null;

    private MulticastSocket ms;
    private static String MulticastHost = "238.9.9.1";
    private static int PORT = 8302;
    InetAddress receiveAddress;
    String result = "";

    private int interFlag = -1;        //技师或消费标识

    private YouhuiDialog youHuiDialog = null;
    private MediaPlayer mediaPlayer = null;
    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;
    private String adUrl;
    private ImageView myImg;
    private FunctionDialog functionDialog;
    private AboutDialog aboutDialog;
    private int[] mHitsCode = new int[8];// 保存上下左右键值
    private int[] mKeyCode = {KeyEvent.KEYCODE_DPAD_UP,KeyEvent.KEYCODE_DPAD_UP,KeyEvent.KEYCODE_DPAD_DOWN,
            KeyEvent.KEYCODE_DPAD_DOWN,KeyEvent.KEYCODE_DPAD_LEFT,KeyEvent.KEYCODE_DPAD_LEFT,
            KeyEvent.KEYCODE_DPAD_RIGHT,KeyEvent.KEYCODE_DPAD_RIGHT};
    private IjkVideoView mIjkVideoView;
    private PlayerManager mPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TAG = this.getClass().getCanonicalName();
        app = (MyApplication) getApplicationContext();
        EventBus.getDefault().post(new GetScrollMessage());

        if (!app.serviceInit) {
            EventBus.getDefault().post(new SyncCallEvent());
            app.setStart(true);
        }

        setContentView(R.layout.activity_main3);
        findView();
        this.className = this.getClass().getName();
        checkVod();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, "onPause");
        if(mPlayer != null && mPlayer.isPlaying()){
            mPlayer.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume");
        //要解除静音两次。。否则在3128的盒子上会没有声音
        HardwareInterface.setMuteFlag(false);
        HardwareInterface.setMuteFlag(false);
        if(mPlayer != null && !mPlayer.isPlaying()){
            mPlayer.start();
        }
        handlerMsg.post(new Runnable() {

            @Override
            public void run() {
                if (!app.getTopActivity().contains("NativeVideoPlayerActivity")) {
                    EventBus.getDefault().post(new HeaderUpdateEvent());
                }
            }
        });

        if (!app.serviceInit) {
            initUdpRev();
            handlerMsg.sendEmptyMessageDelayed(START_INIT, 4000);

            Log.i("login", "尝试登录");
            handlerMsg.sendEmptyMessageDelayed(LOGIN, 1000);

            NetworkStateChecker.getInstance().start(this);
            app.serviceInit = true;
        }
    }

    private void findView() {
        //surfaceView = findViewById(R.id.surface_view);
        myImg = findViewById(R.id.home_img);
    }

    private void initUdpRev() {
        new Thread() {
            public void run() {
                try {
                    ms = new MulticastSocket(PORT);
                    receiveAddress = InetAddress.getByName(MulticastHost);
                    ms.joinGroup(receiveAddress);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                byte data[] = new byte[512];
                DatagramPacket dp = new DatagramPacket(data, 512);

                while (true) {
                    try {
                        ms.receive(dp);
                        result = new String(data, 0, dp.getLength());
                        Message msg = new Message();
                        msg.what = UDP_REV_DATA;
                        handlerMsg.sendMessage(msg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }

            ;
        }.start();
    }

    private void checkVersionInfo() {

        // 判断服务器的API的版本是否可以
        if (MyApplication.serverApiVersion != null
                && !MyApplication.serverApiVersion.equals("")) {
            String version_s[] = MyApplication.serverApiVersion.split("\\.");
            String version_c[] = Constants.API_VERSION.split("\\.");
            Log.i(TAG, "服务器API版本:" + MyApplication.serverApiVersion + "---"
                    + "需要的API版本:" + Constants.API_VERSION);

            if (version_s.length >= 3) {
                if (Integer.parseInt(version_s[0]) >= Integer
                        .parseInt(version_c[0])
                        && Integer.parseInt(version_s[1]) >= Integer
                        .parseInt(version_c[1])
                        && Integer.parseInt(version_s[2]) >= Integer
                        .parseInt(version_c[2])) {

                } else {
                    CustomDialog.Builder builder = new CustomDialog.Builder(
                            this);
                    builder.setTitle("不支持的服务器API版本->"
                            + MyApplication.serverApiVersion);
                    builder.setFirstButton(getString(R.string.yes),
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface di, int arg1) {
                                    di.dismiss();
                                }
                            });

                    CustomDialog d = builder.create();
                    d.show();
                }
            }
        }
        app.setSystemVersion(HardwareInterface.getBoardNameAndVersion());
    }

    //检测是否需要播放背景视频
    private void checkVod() {
        if (SysConf.extendConfGetValue(SysConf.HOTEL_VOD, "0").equals("1")) {
            mIjkVideoView = findViewById(R.id.ijk_video_view);
            mIjkVideoView.setVisibility(View.VISIBLE);
            initPlayerManager();
            initHomeVideoAd();
        }
        /*if (SysConf.extendConfGetValue(SysConf.HOTEL_VOD, "0").equals("1")) {
            adUrl = MyApplication.getHostResUrl() + "upload/myres/ad1.mp4";
            surfaceView.setVisibility(View.VISIBLE);
            //获取SurfaceHolder 可以通过该接口来操作SurfaceView中的Surface
            surfaceHolder = surfaceView.getHolder();

            //设置Meiaplayer的准备监听
            surfaceHolder.addCallback(new SurfaceHolder.Callback() {
                //当SurfaceView中Surface创建时回掉
                //该方法表示Surface已经创建完成，可以在该方法中进行绘图操作
                @Override
                public void surfaceCreated(SurfaceHolder holder) {
                    HardwareInterface.setMuteFlag(false);
                    try {
                        // 创建一个MediaPlayer对象
                        if (mediaPlayer == null) {
                            mediaPlayer = new MediaPlayer();
                        }

                        if (mediaPlayer.isPlaying()) {
                            mediaPlayer.stop();
                            mediaPlayer.release();
                            mediaPlayer = null;
                            mediaPlayer = new MediaPlayer();
                        }
                        // 设置播放的视频数据源
                        mediaPlayer.setDataSource(TabHostActivity.this, Uri.parse(adUrl));
                        mediaPlayer.setLooping(true);

                        // 将视频输出到SurfaceView
                        mediaPlayer.setDisplay(holder);
                        // 播放准备，使用异步方式，配合OnPreparedListener
                        mediaPlayer.prepareAsync();
                        // 设置相关的监听器
                        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                            @Override
                            public void onPrepared(MediaPlayer mp) {
                                //准备完成后播放
                                mediaPlayer.start();
                            }
                        });
                        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

                            @Override
                            public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
                                Log.e("medio", "onError");
                                return false;
                            }
                        });

                    } catch (IllegalArgumentException e) {
                        Log.e("medio", "IllegalArgumentException:" + e.getMessage());
                        e.printStackTrace();
                    } catch (SecurityException e) {
                        Log.e("medio", "SecurityException:" + e.getMessage());
                        e.printStackTrace();
                    } catch (IllegalStateException e) {
                        Log.e("medio", "IllegalStateException:" + e.getMessage());
                        e.printStackTrace();
                    } catch (IOException e) {
                        Log.e("medio", "IOException:" + e.getMessage());
                        e.printStackTrace();
                    }
                }

                @Override
                public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                }

                //当Surface销毁时候，同时把MediaPlayer也销毁
                @Override
                public void surfaceDestroyed(SurfaceHolder holder) {
                    if (mediaPlayer != null) {
                        mediaPlayer.stop();
                        mediaPlayer.reset();
                        //释放资源
                        mediaPlayer.release();
                        mediaPlayer = null;
                    }
                }
            });
        }*/
    }

    /**
     * 初始化软件播放器
     */
    private void initPlayerManager(){
        try {
            mPlayer = new PlayerManager(this, mIjkVideoView);
            mPlayer.setFullScreenOnly(true);
            mPlayer.setScaleType(PlayerManager.SCALETYPE_FITPARENT);
            mPlayer.setPlayerStateListener(this);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private List<HomeAdVideoBean> mHomeAdVideoBeanList = new ArrayList<>();

    /**
     * 初始化首页视频广告
     */
    private void initHomeVideoAd(){
        try{
            int adCount = 0;
            adCount = Integer.parseInt(SysConf.extendConfGetValue(SysConf.SYS_CONF_AD_COUNT, "0"));
            if(adCount > 0){
                for(int i = 0;i < adCount;i ++){
                    HomeAdVideoBean homeAdVideoBean = new HomeAdVideoBean();
                    homeAdVideoBean.setAdPath(MyApplication.getHostResUrl() + "upload/myres/ad" + (i + 1) + ".mp4");
                    homeAdVideoBean.setError(false);
                    mHomeAdVideoBeanList.add(homeAdVideoBean);
                }
                playHomeVideoAd();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private HomeAdVideoBean mHomeAdVideoBean = null;

    private void playHomeVideoAd(){
        Log.i(TAG, "播放列表长度：" + mHomeAdVideoBeanList.size());
        if(mHomeAdVideoBeanList.size() > 0){
            if (mHomeAdVideoBean == null){
                mHomeAdVideoBean = mHomeAdVideoBeanList.get(0);
            }else {
                int pos = mHomeAdVideoBeanList.indexOf(mHomeAdVideoBean);
                //Log.i(TAG, "pos=" + pos);
                if(pos + 1 < mHomeAdVideoBeanList.size()){
                    mHomeAdVideoBean = mHomeAdVideoBeanList.get(pos + 1);
                }else {
                    mHomeAdVideoBean = mHomeAdVideoBeanList.get(0);
                }
            }
        }

        if(mHomeAdVideoBean != null){
            //Log.i(TAG,"播放视频！");
            String adUrl = mHomeAdVideoBean.getAdPath();
            //Log.i(TAG, "播放链接：" + adUrl);
            mPlayer.play(adUrl);
        }
    }

    /**
     * 判断是List里面是否有可以播放的视频
     * @return
     */
    private boolean adCanPlay(){
        for (HomeAdVideoBean homeAdVideoBean: mHomeAdVideoBeanList){
            if (!homeAdVideoBean.isError()){
                return true;
            }
        }
        return false;
    }

    /************第三方IJK库要实现的方法***********/
    @Override
    public void onLoading() {
        Log.i(TAG,"onLoading");
    }

    @Override
    public void onPlay() {
        Log.i(TAG,"onPlay");
        if(mHomeAdVideoBean != null){
            mHomeAdVideoBean.setError(false);
        }
    }

    @Override
    public void onComplete() {
        Log.i(TAG,"onComplete");
        if (adCanPlay()){
            playHomeVideoAd();
        }
    }

    @Override
    public void onError() {
        Log.i(TAG, "onError");
        if (!mIjkVideoView.isPlaying()) {
            if(mHomeAdVideoBean != null){
                mHomeAdVideoBean.setError(true);
            }
        }
        if(adCanPlay()){
            playHomeVideoAd();
        }
    }
    /************第三方IJK库要实现的方法***********/

    @Override
    protected void onStart() {
        super.onStart();

        Message msg = new Message();
        msg.what = CHANGE_BG;
        handlerMsg.sendMessage(msg);
    }

    /*
     * 网络状态变化
     */
    public void onEventMainThread(LoginEvent e) throws IOException {
        Log.i("login", "登录事件.................");
        synchronized (this) {
            Log.i("login", "来了.................");
            if (e.isOk()) {// 已经开通
                handlerMsg.sendEmptyMessageDelayed(UPDATE_HEADER, 100);
                handlerMsg.sendEmptyMessageDelayed(CHECK_INVALID_DAY, 100);
                //隐藏无开通提示窗
                if (aDialog != null) {
                    aDialog.cancel();
                }
            } else {// 提示尚未开通
                if (!isUnLoginTipsed) {
                    System.out.println("设备尚未开通");
                    isUnLoginTipsed = true;
                    // TipsUtil.deviceUnable(this, MyApplication.getMAC());
                    String tips = "设备尚未开通:";
                    //1:开启,0:停用,-1过期,-2没有UKey
                    if (e.getDevice().getStatus().equals(0)) {
                        tips = "本设备已禁用:";
                    } else if (e.getDevice().getStatus().equals(-1)) {
                        tips = "U盾过期:";
                    } else if (e.getDevice().getStatus().equals(-2)) {
                        tips = "没插UKey:";
                    }

                    b = new Builder(this);
                    b.setTitle(tips + MyApplication.getMAC());
                    b.setCancelable(false);
                    b.setOnKeyListener(new OnKeyListener() {

                        @Override
                        public boolean onKey(DialogInterface arg0, int arg1,
                                             KeyEvent arg2) {
                            if (MyKeyEventCode.KEYCODE_SET == arg2.getKeyCode()) {
                                Intent intent = new Intent(Intent.ACTION_MAIN);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                intent.setClassName("com.ly.hotel",
                                        "com.ly.hotel.view.setting.UserGuideActivity");
                                startActivity(intent);
                            }

                            return false;
                        }
                    });
                    aDialog = b.create();
                    aDialog.show();
                }
            }
        }
    }

    private synchronized void login() {
        if (MyApplication.isLogined()) {
            Log.i("login", "已经登录了");
            return;
        }
        app.setLogined(false);
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if (!MyApplication.serverAssess) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //串口初始化
                } else {

                    try {
                        Device device = SPAService.login(MyApplication.getMAC());
                        LoginEvent le = new LoginEvent();
                        le.setDevice(device);
                        if (device != null && device.getStatus() != 0) {
                            le.setOk(true);
                            le.setDeviceName(device.getName());
                            ((MyApplication) getApplication()).setDeviceInfo(device);
                            if (!device.getName().equals(MyApplication.myRoomNo)) {
                                MyApplication.myRoomNo = device.getName();
                                SharedPreferencesConfig.setRoomNo(TabHostActivity.this, device.getName());
                            }
                            Log.i("login", "登录完成");
                            app.setLogined(true);
                            //登录完成后，获取UKey信息
                            try {
                                SPAService.getUKey(MyApplication.getMAC(), app);
                                Log.i("Ukey", "获取U盾授权，初始化相关接口。");

                                if (!MyApplication.mylicense.isEmpty()) {
                                    Log.i(TAG, "UKey准备好了，重新加载一次底部图标");
                                    handlerMsg.sendEmptyMessageDelayed(FLASH_LAYOUT, 500);
                                    handlerMsg.sendEmptyMessageDelayed(SHOW_AUTH_TIPS, 5000);
                                }

                            } catch (HttpRequestFailException e) {
                                Log.e("Ukey", "U盾数据获取出错，重新获取之!" + e.getMessage() + "");
                                EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_BUGS_REPORT_ERROR + "U盾数据获取失败(" + e.getMessage() + ")"));
                                try {
                                    Thread.sleep(2000);
                                    SPAService.getUKey(MyApplication.getMAC(), app);
                                    Log.i("Ukey", "再次获取U盾授权，初始化相关接口。");
                                } catch (InterruptedException e1) {
                                    e1.printStackTrace();
                                }
                            }

							/*
                             * 新建一个任务检测机器是否能联网，如果能联网，就不需要通过代理了
							 */
                            checkInternet();
                        } else {
                            // 设备被停用或者没被后台登记
                            Log.i("login", "设备被停用或者没被后台登记");
                            le.setOk(false);
                        }
                        EventBus.getDefault().post(le);

                        if (login_in_timer != null) {
                            login_in_timer.cancel();
                            login_in_timer = null;
                        }
                    } catch (Exception e) {
                        Log.e("login", "登录失败,Exception：" + e.getMessage());

                        TabHostActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (!isLoginfailBefore) {
                                    Toast.makeText(TabHostActivity.this, "登录失败.",
                                            Toast.LENGTH_SHORT).show();
                                    isLoginfailBefore = true;
                                }
								
								/*//失败了再次登录一次
								login();*/
                                handlerMsg.sendEmptyMessageDelayed(LOGIN, 3000);

                                //登录失败就从本地初始化电视频道
                                if (app.getLiveList() == null) {
                                    List<LiveManagement> list = new Vector<LiveManagement>();
                                    try {
                                        list = AtvUtil.getTvlistFromLlocal();
                                    } catch (NumberFormatException e) {
                                        e.printStackTrace();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    app.setLiveList(list);
                                }
                            }
                        });
                        app.setLogined(false);
                    }
                }

                //只会初始化一次的，这个方法里面会判断，初始化成功就不会再初始化，否则会占用大量的fd，导致系统卡死
                HardwareInterface.initSerial(getBaseContext(), true);
            }

            ;
        };

        if (login_in_timer == null) {
            login_in_timer = new Timer(true);
            login_in_timer.schedule(task, 100, 2000);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NetworkStateChecker.getInstance().stop(this);
    }

    private void checkMacInfo() {
        // 判断MAC地址是否为初始MAC
        String mac = MyApplication.getMAC();
        String checkMac = null;
        if (Build.BOARD.equals(Constants.BOARD_TYPE_6A648_NAME)) {
            checkMac = "00:30:1b:ba:02:db";
        }
        if (mac.equals(checkMac)) {

            CustomDialog.Builder builder = new CustomDialog.Builder(this);
            builder.setTitle("非法MAC地址->" + mac);
            builder.setFirstButton(getString(R.string.yes),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface di, int arg1) {
                            di.dismiss();
                        }
                    });

            CustomDialog d = builder.create();
            d.show();
        }
    }

    private static class ThisHandler extends Handler {
        private WeakReference<TabHostActivity> wrActivity;

        public ThisHandler(TabHostActivity activity) {
            wrActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message message) {
            final TabHostActivity act = wrActivity.get();
            if (act != null) {
                switch (message.what) {
                    case LOGIN:
                        act.login();
                        break;

                    case UPDATE_HEADER:
                        try {
                            act.update_date_time(MyApplication.getDeviceInfo());
                            //获取完系统时间之后，就可以判断是否需要弹出刷手牌登录的页面了
                            String enable = SysConf.extendConfGetValue(SysConf.SYS_CONF_USER_LOGIN_DIALOG, "0");
                            if (enable.equals("1") && MyApplication.haveCardReader) {
                                sendEmptyMessageDelayed(SHOW_LOGIN_DIALOG, 1000);
                            }

                            EventBus.getDefault().post(new HeaderUpdateEvent());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        break;
                    case CHECK_INVALID_DAY:
                        Log.i("ukey", "过期时间：" + MyApplication.ukeyInvalidTime + ",服务器时间:" + MyApplication.startUpTime);
                        long day = 0;
                        java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
                        java.util.Date beginDate;
                        java.util.Date endDate;

                        try {
                            beginDate = format.parse(MyApplication.ukeyInvalidTime);
                            endDate = format.parse(MyApplication.startUpTime);
                            day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
                            //System.out.println("相隔的天数="+day);
                            Log.i("ukey", "相隔的天数：" + day);
                            MyApplication.ukeyInvalidDays = day;
                            if (day > 0) {
                                if (hasMessages(SHOW_AUTH_TIPS)) {
                                    removeMessages(SHOW_AUTH_TIPS);
                                }
                                MyApplication.licenseTimeOut = true;
                                sendEmptyMessageDelayed(SHOW_AUTH_TIPS, 3000);
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                        break;

                    case SHOW_AUTH_TIPS:

                        if (MyApplication.licenseTimeOut || MyApplication.ukeyInvalidDays >= -10) {

                            Intent intent1 = new Intent(Intent.ACTION_MAIN);
                            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent1.setClassName("com.ly.hotel", "com.ly.hotel.view.AuthTipsActivity");
                            act.startActivity(intent1);
                        }
                        break;
                    case START_INIT:
                        act.checkVersionInfo();
                        break;

                    case FLASH_LAYOUT:
                        EventBus.getDefault().post(new UpdateBottomView());
                        break;

                    case START_SETTING:
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setClassName("com.ly.hotel", "com.ly.hotel.view.setting.UserGuideActivity");

                        act.startActivity(intent);
                        act.waitSetting = false;

                        break;

                    case SHOW_LOGIN_DIALOG://开机刷手牌
                        UserLoginActivity dialog = new UserLoginActivity(act, R.style.InputDialog);// 创建Dialog并设置样式主题
                        dialog.setCanceledOnTouchOutside(false);
                        dialog.show();
                        break;


                    case CHANGE_BG:
                        act.checkMacInfo();
                        if (act.myImg == null) {
                            return;
                        }
                        if (MyApplication.getBgBitmap() != null) {
                            act.myImg.setImageBitmap(MyApplication.getBgBitmap());
                        } else {
                            File f = new File(Constants.BG_FILE_PATH);
                            if (f.exists()) {
                                Bitmap bgImage = BitmapFactory.decodeFile(Constants.BG_FILE_PATH);
                                if (bgImage != null) {
                                    act.myImg.setImageBitmap(bgImage);
                                    MyApplication.setBgBitmap(bgImage);
                                }
                            }
                        }
                        break;
                    case UDP_REV_DATA:
                        Log.i("udp", "result-->" + act.result);
                        if (act.result.startsWith("serverip:")) {
                            String ipport = act.result.replace("serverip:", "");
                            String ip = ipport.split(":")[0];
                            String port = ipport.split(":")[1];

                            if (ip.equals("")) {
                                ip = "172.16.1.255";
                            }
                            if (port.equals("")) {
                                port = "8081";
                            }

                            //广播德芯apk的设置
                            String ACTION = "com.ly.broadcast.PreSettingReceiver";
                            Intent intent1 = new Intent();
                            intent1.setAction(ACTION);
                            intent1.putExtra("serverip", ip + ":" + port);
                            MyApplication.getContext().sendBroadcast(intent1);

                            if (!SharedPreferencesConfig.getSpaServer(act).contains(ipport)) {
                                //只有不相同才需要重新设置
                                SharedPreferencesConfig.setSpaServer(act, ip + ":" + port);
                                MyApplication.setHost(SharedPreferencesConfig.getSpaServer(act));

                                //通过产生一个空指针来重启apk，达到切换语言的功能
                                //关闭自己的日志上报系统
                                CrashHandler.rebootNoLog = true;
                                //关闭腾讯的日志上报系统
                                CrashReport.closeCrashReport();
                                CrashReport.closeBugly();

                                //清理一些没用的服务
                                InitActivity.stopService(act, "SPABackService", SPABackService.class);
                                InitActivity.stopService(act, "MyCloudBackService", MyCloudBackService.class);
                                //自杀吧
                                String fuckNanMei = null;
                                fuckNanMei.equals("good");
                            } else {
                                Log.i("udp", "已经设置好了，不需要再设置..");
                            }
                        }
                        break;
                }

            }
        }
    }

    @Override
    public boolean onKeyDown(final int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_0) {
            if (waitSetting == true) {
                handlerMsg.removeMessages(START_SETTING);
                waitSetting = false;
            }
        } else if (keyCode == KeyEvent.KEYCODE_MENU) {        //菜单关于
            startAboutDialog();
        }else if (keyCode == KeyEvent.KEYCODE_DPAD_UP){
            System.arraycopy(mHitsCode, 1, mHitsCode, 0, mHitsCode.length - 1);
            mHitsCode[mHitsCode.length -1] = KeyEvent.KEYCODE_DPAD_UP;
        }else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN){
            System.arraycopy(mHitsCode, 1, mHitsCode, 0, mHitsCode.length - 1);
            mHitsCode[mHitsCode.length -1] = KeyEvent.KEYCODE_DPAD_DOWN;
        }else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT){
            System.arraycopy(mHitsCode, 1, mHitsCode, 0, mHitsCode.length - 1);
            mHitsCode[mHitsCode.length -1] = KeyEvent.KEYCODE_DPAD_LEFT;
        }else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT){
            System.arraycopy(mHitsCode, 1, mHitsCode, 0, mHitsCode.length - 1);
            mHitsCode[mHitsCode.length -1] = KeyEvent.KEYCODE_DPAD_RIGHT;
            if (Arrays.equals(mHitsCode,mKeyCode)){// 适配点击遥控器的上上下下左左右右打开法律声明界面
                startAboutDialog();
            }
        }else {
            int action = MyKeyEventCode.getAction(keyCode);
            Log.i("action", "getAction(keyCode)=" + action);
            switch (action) {
                case MyKeyEventCode.ACTION_SET:// 操作指南
                    if (!waitSetting) {
                        Message msg = new Message();
                        msg.what = START_SETTING;
                        handlerMsg.sendMessageDelayed(msg, 2000);
                        waitSetting = true;
                    }
                    break;
                case MyKeyEventCode.ACTION_CALL:// 呼叫
                    if (app.isBtnItemEnable("呼叫")) {
                        if (event.getRepeatCount() == 0) {
                            call();
                        }
                    }
                    break;
                case MyKeyEventCode.ACTION_LIUWEI:// 留位
                    //因为南美要去掉留位，所以这么做，但是这样之后生产那边就不能测试刷卡了（生产那边是不连接服务器的）
                    //做成不登录也能使用留位吧。。。。
                    if (MyApplication.myLicenseGetValue("留位").equals(1) || !MyApplication.isLogined()) {
                        liuwei(this);
                    }
                    break;
                case MyKeyEventCode.ACTION_TV:// 电视
                    if (app.getAuthToCompany().contains("未获得授权") || !MyApplication.isLogined()) {
                        ToastUtil.showShortToast(this, "设备未获得授权或者未登录，功能暂不可用。", 2000);
                    } else {
                        tv(this);
                    }
                    break;

                case MyKeyEventCode.ACTION_INTRO:// 介绍
                    if (app.getAuthToCompany().contains("未获得授权") || !MyApplication.isLogined()) {
                        ToastUtil.showShortToast(this, "设备未获得授权或者未登录，功能暂不可用。", 2000);
                    } else {
                        if (app.getShopIntroduce() != null && app.getShopIntroduce().size() > 0) {
                            startIntro();
                        } else {
                            EventBus.getDefault().post(new GetIntro());
                            ProcessWaitingUtil.showProcessDialog(this, "loading..", 1000);
                        }
                    }
                    break;

                case MyKeyEventCode.ACTION_GAME:// 游戏
                    if (app.getAuthToCompany().contains("未获得授权") || !MyApplication.isLogined()) {
                        ToastUtil.showShortToast(this, "设备未获得授权或者未登录，功能暂不可用。", 2000);
                    } else {
                        String gameTitle = getResources().getString(R.string.naviGameName);
                        GameActivity.actionStart(this, gameTitle);
                    }
                    break;

                case MyKeyEventCode.ACTION_INTERNET:// 应用
                    if (app.getAuthToCompany().contains("未获得授权") || !MyApplication.isLogined()) {
                        ToastUtil.showShortToast(this, "设备未获得授权或者未登录，功能暂不可用。", 2000);
                    } else {
                        String appTitle = getResources().getString(R.string.naviAppName);
                        GameActivity.actionStart(this, appTitle);
                    }
                    break;

                case MyKeyEventCode.ACTION_YOUHUI://查询
                    if (app.getAuthToCompany().contains("未获得授权") || !MyApplication.isLogined()) {
                        ToastUtil.showShortToast(this, "设备未获得授权或者未登录，功能暂不可用。", 2000);
                    } else {
                        startQuery();
                    /*EventBus.getDefault().post(new GetYouhuiMsgEvent());
					ProcessWaitingUtil.showProcessDialog(this, "获取消息列表数据中..", 1000);*/
                    }
                    break;

                case MyKeyEventCode.ACTION_CONTORL://客控
                    if (app.getAuthToCompany().contains("未获得授权") || !MyApplication.isLogined()) {
                        ToastUtil.showShortToast(this, "设备未获得授权或者未登录，功能暂不可用。", 2000);
                    } else {
                        if (!TextUtils.isEmpty(SysConf.extendConfGetValue(SysConf.SYS_CONF_GUESTCONTORL_PACKET_NAME, ""))) {
                            boolean downloadFlag = false;
                            String packName = SysConf.extendConfGetValue(SysConf.SYS_CONF_GUESTCONTORL_PACKET_NAME);
                            if (!packName.equals("") && AppUtil.checkAppIsExist(this, packName)) {
                                Log.i("live", "打开guestControl,包名：" + packName);
                                AppUtil.startApp(this, packName);
                            } else {
                                Log.i("live", "不能打开guestControl,包名:" + packName + ":" + AppUtil.checkAppIsExist(this, packName));
                                downloadFlag = true;
                            }

                            if (downloadFlag) {
                                Log.i("live", "下载路径: " + MyApplication.getHostResUrl() + "/upload/tv/" + Constants.CUSTOM_CONTROL_APK_FILE_NAME);
                                new WebInstaller(this, MyApplication.getHostResUrl() + "/upload/tv/"
                                        + Constants.CUSTOM_CONTROL_APK_FILE_NAME, Constants.CUSTOM_TV_APK_ROOT, Constants.CUSTOM_CONTROL_APK_FILE_NAME).downloadAndInstall();
                            }
                        }else {
                            ToastUtil.showShortToast(this, "功能暂不可用。", 2000);
                        }
                    }
                    break;

                case MyKeyEventCode.ACTION_MOVICE:// 电影
                    if (app.getAuthToCompany().contains("未获得授权") || !MyApplication.isLogined()) {
                        ToastUtil.showShortToast(this, "设备未获得授权或者未登录，功能暂不可用。", 2000);
                    } else {
                        if (!TextUtils.isEmpty(SysConf.extendConfGetValue(SysConf.SYS_CONF_IPMOVIE_PACKET_NAME, ""))) {
                            boolean downloadFlag = false;
                            String packName = SysConf.extendConfGetValue(SysConf.SYS_CONF_IPMOVIE_PACKET_NAME);
                            if (!packName.equals("") && AppUtil.checkAppIsExist(this, packName)) {
                                Log.i("live", "打开IPMOVIE,包名:" + packName);
                                //要解除静音两次。。否则在3128的盒子上会没有声音
                                HardwareInterface.setMuteFlag(false);
                                HardwareInterface.setMuteFlag(false);
                                String hotelId = SysConf.extendConfGetValue(SysConf.SYS_CONF_HOTELID, "");
                                String roomNo = MyApplication.getDeviceInfo().getName();
                                AppUtil.startApp(this, packName, MyApplication.getMAC(), hotelId, app.getAuthToCompany(), roomNo);
                            } else {
                                Log.i("live", "不能打开IPMOVIE,包名:" + packName + ":" + AppUtil.checkAppIsExist(this, packName));
                                downloadFlag = true;
                            }

                            if (downloadFlag) {
                                Log.i("live", "下载路径:" + MyApplication.getHostResUrl() + "/upload/tv/" + Constants.CUSTOM_MOVIE_APK_FILE_NAME);
                                new WebInstaller(this, MyApplication.getHostResUrl() + "/upload/tv/"
                                        + Constants.CUSTOM_MOVIE_APK_FILE_NAME, Constants.CUSTOM_TV_APK_ROOT, Constants.CUSTOM_MOVIE_APK_FILE_NAME).downloadAndInstall();
                            }

                        } else {
                            if (app.isAgreeVod || SysConf.extendConfGetValue(SysConf.SYS_CONF_STATEMENT, "1").equals("0")) {
                                startMyVod();
                            } else {
                                LegalDeclarationDialog.Builder builder = new LegalDeclarationDialog.Builder(this);
                                builder.setFirstButton(new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface di, int arg1) {
                                        di.dismiss();
                                    }
                                });
                                builder.setSecondButton(new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface di, int arg1) {
                                        app.isAgreeVod = true;
                                        startMyVod();
                                        di.dismiss();
                                    }
                                });
                                builder.create(false).show();
                            }
                        }
                    }
                    break;
                case MyKeyEventCode.ACTION_EPISODE://电视剧
                    if (app.getAuthToCompany().contains("未获得授权") || !MyApplication.isLogined()) {
                        ToastUtil.showShortToast(this, "设备未获得授权或者未登录，功能暂不可用。", 2000);
                    } else {
                        if (app.isAgreeEpisode || SysConf.extendConfGetValue(SysConf.SYS_CONF_STATEMENT, "1").equals("0")) {
                            startMyEpisode();
                        } else {
                            LegalDeclarationDialog.Builder builder = new LegalDeclarationDialog.Builder(this);
                            builder.setFirstButton(new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface di, int arg1) {
                                    di.dismiss();
                                }
                            });
                            builder.setSecondButton(new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface di, int arg1) {
                                    app.isAgreeEpisode = true;
                                    startMyEpisode();
                                    di.dismiss();
                                }
                            });
                            builder.create(false).show();
                        }
                    }
                    break;

                case MyKeyEventCode.ACTION_MUSIC:// 音乐
                    if (app.getAuthToCompany().contains("未获得授权") || !MyApplication.isLogined()) {
                        ToastUtil.showShortToast(this, "设备未获得授权或者未登录，功能暂不可用。", 2000);
                    } else {
                        if (!TextUtils.isEmpty(SysConf.extendConfGetValue(SysConf.SYS_CONF_IPMUSIC_PACKET_NAME, ""))) {
                            boolean downloadFlag = false;
                            String packName = SysConf.extendConfGetValue(SysConf.SYS_CONF_IPMUSIC_PACKET_NAME);
                            if (!packName.equals("") && AppUtil.checkAppIsExist(this, packName)) {
                                //要解除静音两次。。否则在3128的盒子上会没有声音
                                HardwareInterface.setMuteFlag(false);
                                HardwareInterface.setMuteFlag(false);
                                AppUtil.startApp(this, packName);
                            } else {
                                Log.i("live", "不能打开IPMUSIC,包名:" + packName + ":" + AppUtil.checkAppIsExist(this, packName));
                                downloadFlag = true;
                            }

                            if (downloadFlag) {
                                new WebInstaller(this, MyApplication.getHostResUrl() + "/upload/tv/"
                                        + Constants.CUSTOM_MUSIC_APK_FILE_NAME, Constants.CUSTOM_TV_APK_ROOT, Constants.CUSTOM_MUSIC_APK_FILE_NAME).downloadAndInstall();
                            }

                        } else {
                            if (app.isAgreeMuc || SysConf.extendConfGetValue(SysConf.SYS_CONF_STATEMENT, "1").equals("0")) {
                                startMyMusic();
                            } else {
                                LegalDeclarationDialog.Builder builder = new LegalDeclarationDialog.Builder(this);
                                builder.setFirstButton(new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface di, int arg1) {
                                        di.dismiss();
                                    }
                                });
                                builder.setSecondButton(new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface di, int arg1) {
                                        app.isAgreeMuc = true;
                                        startMyMusic();
                                        di.dismiss();
                                    }
                                });
                                builder.create(false).show();
                            }
                        }
                    }
                    break;

                case MyKeyEventCode.ACTION_MASSAGE:// 信息
                    if (app.getAuthToCompany().contains("未获得授权") || !MyApplication.isLogined()) {
                        ToastUtil.showShortToast(this, "设备未获得授权或者未登录，功能暂不可用。", 2000);
                    } else {
                        startMessage();
                    }
                    break;

                case MyKeyEventCode.ACTION_JISHI:// 技师
                    if(app.getAuthToCompany().contains("未获得授权") || !MyApplication.isLogined()){
                        ToastUtil.showShortToast(this, "设备未获得授权或者未登陆，功能暂不可用。", 2000);
                    }else {
                        if(app.isBtnItemEnable("技师")){
                            if (!SysConf.extendConfGetValue(SysConf.SYS_CONF_JISHI_URL, "").equals("") && action == MyKeyEventCode.ACTION_JISHI) {
                                //如果有配置了网址，就直接通过浏览器打开
                                Intent intent = new Intent();
                                intent.setAction("android.intent.action.VIEW");
                                Uri content_url = Uri.parse(SysConf.extendConfGetValue(SysConf.SYS_CONF_JISHI_URL, ""));
                                intent.setData(content_url);
                                startActivity(intent);
                            } else {
                                interFlag = 0;
                                if (!TextUtils.isEmpty(MyApplication.interfaceVersion) && !TextUtils.isEmpty(MyApplication.pluginCfg)) {
                                    startInterface();
                                } else {
                                    EventBus.getDefault().post(new GetWebInterfaceUrlEvent());
                                    ProcessWaitingUtil.showProcessDialog(this, "loading..", 1000);
                                }
                            }
                        }else {
                            ToastUtil.showShortToast(this, "技师模块未开通。", 2000);
                        }
                    }
                    break;

                case MyKeyEventCode.ACTION_XIAOFEI:// 消费
                    if (app.getAuthToCompany().contains("未获得授权") || !MyApplication.isLogined()) {
                        ToastUtil.showShortToast(this, "设备未获得授权或者未登录，功能暂不可用。", 2000);
                    } else {
                        if (!SysConf.extendConfGetValue(SysConf.SYS_CONF_XIAOFEI_URL, "").equals("") && action == MyKeyEventCode.ACTION_XIAOFEI) {
                            //如果有配置了网址，就直接通过浏览器打开
                            Intent intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            Uri content_url = Uri.parse(SysConf.extendConfGetValue(SysConf.SYS_CONF_XIAOFEI_URL, ""));
                            intent.setData(content_url);
                            startActivity(intent);

                        } else {
                            interFlag = 1;
                            if (!TextUtils.isEmpty(MyApplication.interfaceVersion) && !TextUtils.isEmpty(MyApplication.pluginCfg)) {
                                startInterface();
                            } else {
                                EventBus.getDefault().post(new GetWebInterfaceUrlEvent());
                                ProcessWaitingUtil.showProcessDialog(this, "loading..", 1000);
                            }
                        }
                    }
                    break;
                case MyKeyEventCode.ACTION_ABOUT:// 关于
                    changeLanguage();
                    break;
                default:
                    break;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    //切换语言
    public void changeLanguage() {
        CustomDialog.Builder dialog = new CustomDialog.Builder(this);
        dialog.setTitle(getString(R.string.switch_lang_tips));
        dialog.setFirstButton(getString(R.string.lang_ok), new DialogInterface.OnClickListener() {
            @SuppressWarnings("null")
            @Override
            public void onClick(DialogInterface di, int arg1) {
                //通过产生一个空指针来重启apk，达到切换语言的功能
                //关闭自己的日志上报系统
                EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_POINT_SWITCH_LANG));
                CrashHandler.rebootNoLog = true;
                //关闭腾讯的日志上报系统
                CrashReport.closeCrashReport();
                CrashReport.closeBugly();

                //清理一些没用的服务
                InitActivity.stopService(TabHostActivity.this, "SPABackService", SPABackService.class);
                InitActivity.stopService(TabHostActivity.this, "MyCloudBackService", MyCloudBackService.class);
                ActivityCollector.finishAll();
                //自杀吧
                String fuckNanMei = null;
                fuckNanMei.equals("good");
            }
        });
        dialog.setSecondButton(getString(R.string.lang_cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface di, int arg1) {
                di.dismiss();
            }
        });
        CustomDialog d = dialog.create();
        d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        d.show();
    }

    //查询服务
    private void startQuery() {
        if (functionDialog == null) {
            functionDialog = new FunctionDialog(this, R.style.introDialog);
            functionDialog.setCanceledOnTouchOutside(true);
        }
        functionDialog.show();
        functionDialog.setAdapter();
    }

    //打开本地电影
    private void startMyVod() {
        Intent intent = new Intent(this, VodActivity.class);
        startActivity(intent);
    }

    //打开本地电视剧
    private void startMyEpisode() {
        Intent intente = new Intent(this, EpisodeActivity.class);
        startActivity(intente);
    }

    //打开关于
    private void startAboutDialog() {
        if (aboutDialog == null) {
            aboutDialog = new AboutDialog(MyApplication.getContext(), R.style.introDialog);//创建Dialog并设置样式主题
            aboutDialog.setCanceledOnTouchOutside(true);//设置点击Dialog外部任意区域关闭Dialog
            aboutDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE);
        }
        aboutDialog.show();
        aboutDialog.setRoomVer();
    }

    //打开本地音乐
    private void startMyMusic() {
        Intent mintent = new Intent(this, MusicActivity.class);
        startActivity(mintent);
    }

    public void startIntro() {
        List<Serve> data = app.getShopIntroduce();
        String title = getResources().getString(R.string.naviIntroName);
        IntroActivity.actionStart(this, title, data, 0);
    }

    //打开技师
    public void startInterface() {
        if (MyApplication.interfaceVersion.contains("NM")) {
            //南美
            if (interFlag == 0) {
                ToastUtil.showShortToast(this, "该接口尚未开通！", 2000);
                EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_JISHI + "\t" + MyApplication.interfaceVersion));
            } else {
                Intent intent = new Intent(this, NmXiaoFeiActivity.class);
                startActivity(intent);
                EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_XIAOFEI + "\t" + MyApplication.interfaceVersion));
            }
        } else if (MyApplication.interfaceVersion.contains("JXD")) {
            //捷信达
            if (interFlag == 0) {
                Intent intent = new Intent(this, JxdJSActivity.class);
                startActivity(intent);
            } else {
                Intent intent = new Intent(this, JxdXiaoFeiActivity.class);
                startActivity(intent);
            }
        } else if (MyApplication.interfaceVersion.contains("JG")) {
            //金贵
            if (interFlag == 0) {
                Intent intent = new Intent(this, JgActivity.class);
                startActivity(intent);
            } else {
                Intent intent = new Intent(this, JgActivity.class);
                startActivity(intent);
            }
        } else if (MyApplication.interfaceVersion.contains("JYT")) {
            //精易通
            if (interFlag == 0) {
                Intent intent = new Intent(this, JytJSActivity.class);
                startActivity(intent);
            } else {
                Intent intent = new Intent(this, JytXiaoFeiActivity.class);
                startActivity(intent);
            }
        } else if (MyApplication.interfaceVersion.contains("PP")) {
            //PP
            if (interFlag == 0) {
                Intent intent = new Intent(this, PPJSActivity.class);
                startActivity(intent);
            } else {
                Intent intent = new Intent(this, PPXFActivity.class);
                startActivity(intent);
            }
        } else {
            ToastUtil.showShortToast(this, "该接口尚未开通！", 2000);
        }
    }

    public void onEventMainThread(UpdateInterfaceEvent e) {
        if (interFlag > -1) {
            ProcessWaitingUtil.closeProcessDialog();
            if (e.isValidUpdate()) {
                startInterface();
            } else {
                if (TextUtils.isEmpty(MyApplication.interfaceVersion)) {
                    ToastUtil.showShortToast(this, "请在后台配置接口分组！No Data!", 2000);
                } else {
                    ToastUtil.showShortToast(this, "请在后台写入插件配置！No Data!", 2000);
                }
            }
        }
    }

    //收到接口更新信息
    public void onEventMainThread(UpdateIntro e) {
        ProcessWaitingUtil.closeProcessDialog();
        if (e.isValidUpdate()) {
            startIntro();
        } else {
            ToastUtil.showShortToast(this, "抱歉，无介绍信息！ No Data!", 2000);
        }
    }

    //消息弹窗
    private void startMessage() {
        Intent intent = new Intent(this, MessageActivity.class);
        startActivity(intent);
    }

    public void onEventMainThread(UpdateYouhuiMsgEvent e) {
        ProcessWaitingUtil.closeProcessDialog();
        if (e.isValidUpdate()) {
            if (youHuiDialog == null) {
                youHuiDialog = new YouhuiDialog(this, R.style.introDialog);//创建Dialog并设置样式主题
                youHuiDialog.setCanceledOnTouchOutside(true);//设置点击Dialog外部任意区域关闭Dialog
                youHuiDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
            }
            youHuiDialog.show();
            youHuiDialog.InitView(app.getMessages());
        } else {
            ToastUtil.showShortToast(this, "抱歉，无优惠信息！No Data!", 2000);
        }
    }

}
